package com.sz10.p2p.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.sz10.p2p.Constants;
import com.sz10.p2p.mapper.UserMapper;
import com.sz10.p2p.service.UserService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Service(interfaceClass = UserService.class, version = "1.0.0", timeout = 15000)
public class UserServiceImpl implements UserService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 使用双重验证+同步代码块解决缓存击穿问题
     *
     * @return
     */

    @Override
    public Integer queryAllUserCount() {
        //先得到redis缓存中获取总人数
        Integer allUserCount = (Integer) redisTemplate.opsForValue().get(Constants.ALL_USER_COUNT);
        if (!ObjectUtils.allNotNull(allUserCount)) {
            synchronized (this) {
                allUserCount = (Integer) redisTemplate.opsForValue().get(Constants.ALL_USER_COUNT);
                if (!ObjectUtils.allNotNull(allUserCount)) {
                    //判断没有再去数据库查询，然后保存一份到redis中，在返回
                    allUserCount = userMapper.selectUserCount();
                    redisTemplate.opsForValue().set(Constants.ALL_USER_COUNT, allUserCount);
                }
            }
        }
        return allUserCount;
    }
}
